package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.HistoryService;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @author jack
 * @data 2023 12:47
 */
@Service
public class HistoryServiceImpl implements HistoryService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 加载当前用户的历史记录
     *
     * @return
     */
    @Override
    public ResponseResult load() {
        //1. 拿到当前登录用户的id
        Integer userId = ApUserThreadLocalUtil.getUser();

        //2. 校验：如果id为null或者id为0(游客)，直接返回空的历史记录
        if (userId == null || userId == 0)
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

        //3. 根据用户id查询mongoDB中ap_user_search表
        List<ApUserSearch> list = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);

        //4. 返回查询结果
        return ResponseResult.okResult(list);
    }

    /**
     * 新增或更新用户搜索历史记录
     *
     * @param searchWords
     */
    @Override
    public void saveOrUpdate(String searchWords) {
        //1. 查询当前用户搜索记录
        Integer userId = ApUserThreadLocalUtil.getUser();
        List<ApUserSearch> list = mongoTemplate.find(Query.query(Criteria.where("userId")
                .is(userId)).with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);

        if (list != null && list.size() > 0) {
            //2. 判断本次搜索的词是否在记录中存在
            boolean isExists = false;
            for (ApUserSearch apUserSearch : list) {
                if (apUserSearch.getKeyword().equals(searchWords)) {
                    //3. 存在：将对应的词更新到当前时间
                    isExists = true;
                    apUserSearch.setCreatedTime(new Date());
                    mongoTemplate.save(apUserSearch);
                }
            }

            if (!isExists) {
                //4. 不存在：判断当前用户搜索词数量是否超过10
                if (list.size() < 10) {
                    //5. 没有超过： 新增一条记录
                    ApUserSearch apUserSearch  = new ApUserSearch();
                    apUserSearch.setUserId(userId);
                    apUserSearch.setKeyword(searchWords);
                    apUserSearch.setCreatedTime(new Date());
                    mongoTemplate.save(apUserSearch);
                } else {
                    //6. 超过： 替换最早的所搜记录
                    ApUserSearch oldestSearch = list.get(list.size() - 1);
                    oldestSearch.setKeyword(searchWords);
                    oldestSearch.setCreatedTime(new Date());
                    mongoTemplate.save(oldestSearch);
                }
            }


        }


    }
}
